package com.ddatsh.transaction.core.lifecycle.factory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import javax.persistence.EntityManager;

import com.ddatsh.transaction.core.model.ApplicationContext;
import com.ddatsh.transaction.core.model.CapacityExtQueue;
import com.ddatsh.transaction.core.model.CapacityLimit;
import com.ddatsh.transaction.core.model.TransactionDefinition;

/**
 * 应用上下文工厂，用于构件应用上下文
 * 
 * @author ddatsh
 * @version 1.0
 */
public class ApplicationContextFactory {
	private Properties properties;
	private int capacityExtQueueSize;
	private EntityManager entityManager;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	/**
	 * 初始化应用上下文
	 */
	public void initApplicationContext() {
		List<CapacityLimit> capacityLimits = getCapacityLimits();
		ApplicationContext.init(properties, getTransDefMap(),
				new CapacityExtQueue(capacityExtQueueSize), capacityLimits,
				null);
	}

	@SuppressWarnings("unchecked")
	private List<CapacityLimit> getCapacityLimits() {
		List<CapacityLimit> capacityLimitList=new ArrayList();
		CapacityLimit capacityLimit=new CapacityLimit();
		capacityLimitList.add(capacityLimit);
		return capacityLimitList;
//		return (List<CapacityLimit>) entityManager.createQuery(
//				"select c from " + CapacityLimit.class.getName() + " c")
//				.getResultList();
	}

	@SuppressWarnings("unchecked")
	private Map<String, TransactionDefinition> getTransDefMap() {
		List<TransactionDefinition> transDefs =new ArrayList();
		TransactionDefinition transDef=new TransactionDefinition();
		transDef.setTransCode("0001");
		transDefs.add(transDef);
//		List<TransactionDefinition> transDefs = entityManager.createQuery(
//				"select p from " + TransactionDefinition.class.getName()
//						+ "  p").getResultList();
		
		Map<String, TransactionDefinition> _transDefMap = new ConcurrentHashMap<String, TransactionDefinition>();
		for (TransactionDefinition td : transDefs) {
			_transDefMap.put(td.getTransCode(), td);
		}
		return _transDefMap;
	}

	public int getCapacityExtQueueSize() {
		return capacityExtQueueSize;
	}

	public void setCapacityExtQueueSize(int capacityExtQueueSize) {
		this.capacityExtQueueSize = capacityExtQueueSize;
	}

	public Properties getProperties() {
		return properties;
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}
}